import type { DateTime } from 'luxon'
import { BaseModel, beforeCreate, beforeFetch, column } from '@adonisjs/lucid/orm'
import type { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model'
import { CustomCamelCaseNamingStrategy } from './camel_case_naming_strategy.js'

export default class CommonBaseModel extends BaseModel {
  static namingStrategy = new CustomCamelCaseNamingStrategy()

  serializeExtras() {
    const { status, ...extras } = this.$extras
    return extras
  }

  @column({ isPrimary: true })
  declare id: number

  @column()
  declare fkShopId: number

  @beforeFetch()
  static async globWhere(query: ModelQueryBuilderContract<typeof CommonBaseModel>) {
    const payload = globalThis.user || globalThis.wxPayload
    if (payload?.fkShopId) query.where('fkShopId', payload?.fkShopId)
  }

  @beforeCreate()
  protected static assignAutoFill(data: CommonBaseModel) {
    if (globalThis.user) {
      data.fkShopId = globalThis.user.loginShopId
      data.createUser = globalThis.user.userName
      data.updateUser = globalThis.user.userName
    }

    if (globalThis.wxPayload) data.fkShopId = globalThis.wxPayload.fkShopId
  }

  @column.dateTime({
    serialize: serializeDateTime,
  })
  declare createTime: DateTime

  @column()
  declare createUser: string

  @column.dateTime({
    serialize: serializeDateTime,
    autoUpdate: true,
  })
  declare updateTime: DateTime

  @column()
  declare updateUser: string

  @column.dateTime({
    serialize: serializeDateTime,
  })
  declare deleteTime: DateTime
}

export function serializeDateTime(value: DateTime) {
  return value?.toFormat('yyyy-MM-dd HH:mm:ss')
}

export const moneyTransform = {
  prepare: (value: number) => value * 100,
  consume: (value: number) => value / 100,
}
